const { execSync } = require('child_process');
const { writeFileSync } = require('fs');
const path = require('path');
const { logger } = require('appium-support');

const log = logger.getLogger('SENTRY VERSION');

try {
  // Set the Sentry recommended version
  const env = (process.env.NODE_ENV || 'development').substr(0, 3);
  let version = execSync('npx sentry-cli releases propose-version', {encoding: 'utf8'});
  version = `appium-desktop@${process.platform}-${env}-${version.trim().substr(0, 10)}`;
  log.info(`Setting Sentry release version to ${version}`);

  // Save it as an autogenerated JS export
  writeFileSync(path.resolve(__dirname, 'sentry-version.js'), `/** AUTO-GENERATED DO NOT EDIT **/ module.exports = "${version}";`);
} catch (e) {
  log.error(`Could not establish Sentry version. Reason: ${e.message}`);
  process.exit(1);
}